import json
import datetime

import redis
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views import View
from django_redis import get_redis_connection
from rest_framework.response import Response

from apps.ten_auth.models import Label, User, Question, Reply
from utils.simmiddleware01 import login_required_my
from utils.ten_token import verify_jwt
from utils.to_examine import write_shehe


redis_history = get_redis_connection('history')
redis_hc = get_redis_connection('code')

"""  获取所有标签列表  """
# Create your views.py here.
class AllLabelsView(View):
    def get(self, request):
        label_hc = redis_hc.get('all-labels')
        if label_hc is None:
            labels = Label.objects.all()
            data = []
            for i in labels:
                data.append({
                    'id': i.id,
                    'label_name': i.label_name
                })
            redis_hc.setex('all-labels',24*30*3600, json.dumps(data))
            return JsonResponse(data, safe=False)
        else:
            data = json.loads(label_hc)
            return JsonResponse(data, safe=False)



"""  获取用户关注标签  """
class UserLabelsView(View):
    # @method_decorator(login_required_my, name='get')
    def get(self, request):
        # 获取存入token中的用户信息
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        user = User.objects.get(id=user_id)
        # 获取第三个表中登录用户的关注的数据
        labels = user.labels.all()
        data = []
        for i in labels:
            data.append({
                'id': i.id,
                'label_name': i.label_name
            })
        return JsonResponse(data, safe=False)


"""  标签展示  """
class UserLabelsFullView(View):
    def get(self, request):
        labels = Label.objects.all()
        data = []
        for i in labels:
            users = i.users.all()
            user = []
            for a in users:
                user.append(a.id)
            data.append({
                'id': i.id,
                'label_name': i.label_name,
                'users':  user
            })
        return JsonResponse(data, safe=False)


"""  最新回答的问题  """
class LabelsQuestionView(View):
    # @method_decorator(login_required_my, name='get')
    def get(self, request, id):
        if id == '-1':
            question = Question.objects.filter(replyname__isnull=False).all()
        else:
            label = Label.objects.get(id=id)
            question = label.questions.filter(replyname__isnull=False).all()
        data = []
        for i in question:
            data_time = datetime.date.today()
            # 将字符串转换为datetime对象
            datetime_obj = datetime.datetime.strptime(str(i.updatetime), '%Y-%m-%d %H:%M:%S.%f%z')
            # 将datetime对象转换为指定格式的字符串
            formatted_time = datetime_obj.strftime('%Y-%m-%d')
            # dateted_time = data_time.strftime('%Y-%m-%')
            if formatted_time == str(data_time):
                use = User.objects.get(id=i.user_id)
                labels = i.labels.all()
                lab = []
                for e in labels:
                    lab.append(e.label_name)
                data.append({
                    'id': i.id,
                    'createtime': str(i.createtime),
                    'labels': lab,
                    'reply': i.reply,
                    'replyname': i.replyname,
                    'replytime': str(i.replytime),
                    'title': i. title,
                    'unuseful_count': i. unuseful_count,
                    'useful_count': i. useful_count,
                    'user': use.username,
                    'visits': i.visits
                })
            else:
                continue
        return JsonResponse(data, safe=False)


"""  热门回答的问题  """
class HotLabelsQuestionView(View):
    # @method_decorator(login_required_my, name='get')
    def get(self, request, id):
        if id == '-1':
            question = Question.objects.filter(useful_count__gt=0).order_by('-useful_count')
        else:
            label = Label.objects.get(id=id)
            question = label.questions.filter(useful_count__gte=5).all()
        data = []
        for i in question:
            use = User.objects.get(id=i.user_id)
            labels = i.labels.all()
            lab = []
            for e in labels:
                lab.append(e.label_name)
            data.append({
                'id': i.id,
                'createtime': str(i.createtime),
                'labels': lab,
                'reply': i.reply,
                'replyname': i.replyname,
                'replytime': str(i.replytime),
                'title': i. title,
                'unuseful_count': i. unuseful_count,
                'useful_count': i. useful_count,
                'user': use.username,
                'visits': i.visits
            })
        return JsonResponse(data, safe=False)


"""  等待回答的问题  """
class WaitLabelsQuestionView(View):
    # @method_decorator(login_required_my, name='get')
    def get(self, request, id):
        if id == '-1':
            question = Question.objects.filter(replyname=None, replytime=None).all()
        else:
            label = Label.objects.get(id=id)
            question = label.questions.filter(replyname=None, replytime=None).all()
        data = []
        for i in question:
            use = User.objects.get(id=i.user_id)
            labels = i.labels.all()
            lab = []
            for e in labels:
                lab.append(e.label_name)
            data.append({
                'id': i.id,
                'createtime': str(i.createtime),
                'labels': lab,
                'reply': i.reply,
                'replyname': i.replyname,
                'replytime': str(i.replytime),
                'title': i. title,
                'unuseful_count': i. unuseful_count,
                'useful_count': i. useful_count,
                'user': use.username,
                'visits': i.visits
            })
        return JsonResponse(data, safe=False)


"""  发布问题  """
class CreateQuestionsView(View):
    @method_decorator(login_required_my, name='post')
    def post(self, request):
        # 获取存入token中的用户信息
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        user = User.objects.get(id=user_id)
        data = json.loads(request.body)
        content = data.get('content')
        resulta = write_shehe(content)
        labels = data.get('labels')
        title = data.get('title')
        result = write_shehe(title)
        if resulta['conclusionType'] != 1:
            return JsonResponse({'success': False, 'message': '内容不合规'})
        if result['conclusionType'] != 1:
            return JsonResponse({'success': False, 'message': '内容不合规'})
        try:
            question = Question.objects.create(user=user, title=title, content=content)
            for i in labels:
                label = Label.objects.get(id=i)
                question.labels.add(label)
        except Exception as e:
            return e
        return JsonResponse({'success': True, 'message': '发布成功！'})

"""  问题详情  """
class GetQuestionsView(View):
    # @method_decorator(login_required_my, name='get')
    def get(self, request, id):
        # 获取存入token中的用户信息
        # token = request.headers.get('Authorization')[4:]
        # user_id = verify_jwt(token)['user_id']
        # user = User.objects.get(id=user_id)
        question = Question.objects.get(id=id)
        question.visits += 1
        question.save()
        us = User.objects.get(id=question.user_id)
        com_question = Reply.objects.filter(problem_id=question.id, type=0).all()
        comm_question = Reply.objects.filter(problem_id=question.id, type=2).all()
        labels = question.labels.all()
        lab = []
        for e in labels:
            lab.append(e.label_name)
        comment_question = []
        for i in com_question:
            use = User.objects.get(id=i.user_id)
            subs = []
            comment_question.append({
                'id': i.id,
                'content': i.content,
                'createtime': str(i.createtime),
                'useful_count': i. useful_count,
                'problem': i.problem_id,
                'unuseful_count': i.unuseful_count,
                'subs': subs,
                'user': {'id': use.id, 'username': use.username, 'avatar': use.avatar},
                'parent': i.parent_id
            })
        answer_question = []
        for a in comm_question:
            sub = Reply.objects.filter(problem_id=question.id, parent_id=a.id, type=1).all()
            use = User.objects.get(id=a.user_id)
            subs = []
            for c in sub:
                usa = User.objects.get(id=c.user_id)
                subs.append({
                    'id': c.id,
                    'content': c.content,
                    'createtime': str(c.createtime),
                    'useful_count': c.useful_count,
                    'problem': c.problem_id,
                    'user': {'id': usa.id, 'username': usa.username, 'avatar': usa.avatar},
                    'unuseful_count': c.unuseful_count,
                })
            answer_question.append({
                'id': a.id,
                'content': a.content,
                'createtime': str(a.createtime),
                'useful_count': a.useful_count,
                'problem': a.problem_id,
                'unuseful_count': a.unuseful_count,
                'subs': subs,
                'user': use.username,
                'parent': a.parent_id
            })
        # data.append()
        return JsonResponse({
            'id': question.id,
            'createtime': str(question.createtime),
            'labels': lab,
            'reply': question.reply,
            'replyname': question.replyname,
            'replytime': str(question.replytime),
            'title': question.title,
            'unuseful_count': question.unuseful_count,
            'useful_count': question.useful_count,
            'user': {'id': us.id, 'username': us.username, 'avatar': us.avatar},
            'visits': question.visits,
            'content': question.content,
            'comment_question': comment_question,
            'answer_question': answer_question
        })


"""  问题有用  """
class UseFulQuestionView(View):
    # @method_decorator(login_required_my, name='put')
    def put(self, request, id):
        #获取存入token中的用户信息
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        hist = redis_history.get('useful-q%s-u%s' % (id, user_id))
        uhist = redis_history.get('unuseful-q%s-u%s' % (id, user_id))
        if hist:
            return JsonResponse({'success': False, 'message': '请勿重复操作！'})
        elif uhist:
            redis_history.delete('unuseful-q%s-u%s' % (id, user_id))
            question = Question.objects.get(id=id)
            question.unuseful_count -= 1
            question.useful_count += 1
            question.save()
            redis_history.set('useful-q%s-u%s' % (id, user_id), 1)
            return JsonResponse({'success': True, 'message': '发布成功！'})
        else:
            question = Question.objects.get(id=id)
            question.useful_count += 1
            question.save()
            redis_history.set('useful-q%s-u%s' % (id, user_id), 1)
        return JsonResponse({'success': True, 'message': '发布成功！'})


"""  问题没用  """
class UnUseFulQuestionView(View):
    # @method_decorator(login_required_my, name='put')
    def put(self, request, id):
        # 获取存入token中的用户信息
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        hist = redis_history.get('useful-q%s-u%s' % (id, user_id))
        uhist = redis_history.get('unuseful-q%s-u%s' % (id, user_id))
        if uhist:
            return JsonResponse({'success': False, 'message': '请勿重复操作！'})
        elif hist:
            redis_history.delete('useful-q%s-u%s' % (id, user_id))
            question = Question.objects.get(id=id)
            question.useful_count -= 1
            question.unuseful_count += 1
            question.save()
            redis_history.set('unuseful-q%s-u%s' % (id, user_id), 1)
            return JsonResponse({'success': True, 'message': '操作成功！'})
        else:
            question = Question.objects.get(id=id)
            question.useful_count += 1
            question.save()
            redis_history.set('unuseful-q%s-u%s' % (id, user_id), 1)
        return JsonResponse({'success': True, 'message': '操作成功！'})


"""  回答问题  """
class CreateReplyView(View):
    # @method_decorator(login_required_my, name='post')
    def post(self, request):
        # 获取存入token中的用户信息
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        user = User.objects.get(id=user_id)
        data = json.loads(request.body)
        problem = data.get('problem')
        content = data.get('content')
        types = data.get('type')
        parent = data.get('parent')
        resulta = write_shehe(content)
        if resulta['conclusionType'] != 1:
            return JsonResponse({'success': False, 'message': '输入内容不合规'})
        try:
            reply = Reply.objects.create(user_id=user_id, problem_id=problem,
                                         content=content, type=types)
            question = Question.objects.get(id=problem)
            question.reply += 1
            question.save()
            if parent:
                reply.parent_id = parent
                reply.save()
            question = Question.objects.get(id=problem)
            question.replyname = user.username
            question.replytime = datetime.datetime.now()
            question.save()
        except Exception as e:
            return e
        return JsonResponse({'success': True, 'message': '回答问题成功！'})


"""  回答有用  """
class UsefulReplyView(View):
    def put(self, request, id):
        # 获取存入token中的用户信息
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        hist = redis_history.get('rep-useful-q%s-u%s' % (id, user_id))
        uhist = redis_history.get('rep-unuseful-q%s-u%s' % (id, user_id))
        if hist:
            return JsonResponse({'success': False, 'message': '请勿重复操作！'})
        elif uhist:
            redis_history.delete('rep-unuseful-q%s-u%s' % (id, user_id))
            reply = Reply.objects.get(id=id)
            reply.unuseful_count -= 1
            reply.useful_count += 1
            reply.save()
            redis_history.set('rep-useful-q%s-u%s' % (id, user_id), 1)
            return JsonResponse({'success': True, 'message': '发布成功！'})
        else:
            reply = Reply.objects.get(id=id)
            reply.useful_count += 1
            reply.save()
            redis_history.set('rep-useful-q%s-u%s' % (id, user_id), 1)
        return JsonResponse({'success': True, 'message': '发布成功！'})


"""  回答没用  """
class UnUsefulReplyView(View):
    def put(self, request, id):
        # 获取存入token中的用户信息
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        hist = redis_history.get('rep-useful-q%s-u%s' % (id, user_id))
        uhist = redis_history.get('rep-unuseful-q%s-u%s' % (id, user_id))
        if uhist:
            return JsonResponse({'success': False, 'message': '请勿重复操作！'})
        elif hist:
            redis_history.delete('rep-useful-q%s-u%s' % (id, user_id))
            reply = Reply.objects.get(id=id)
            reply.useful_count -= 1
            reply.unuseful_count += 1
            reply.save()
            redis_history.set('rep-unuseful-q%s-u%s' % (id, user_id), 1)
            return JsonResponse({'success': True, 'message': '操作成功！'})
        else:
            reply = Reply.objects.get(id=id)
            reply.useful_count += 1
            reply.save()
            redis_history.set('rep-unuseful-q%s-u%s' % (id, user_id), 1)
        return JsonResponse({'success': True, 'message': '操作成功！'})


"""  关注标签  """
class UserLikeLabelsView(View):
    def put(self, request, id):
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        user = User.objects.get(id=user_id)
        label = Label.objects.get(id=id)
        user.labels.add(label)
        user.save()
        return JsonResponse({'success': True,'message': '关注成功！'})


"""  取消关注标签  """
class UserUnLikeLabelsView(View):
    def put(self, request, id):
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        user = User.objects.get(id=user_id)
        label = Label.objects.get(id=id)
        user.labels.remove(label)
        user.save()
        return JsonResponse({'success': True, 'message': '取消关注成功！'})


"""  标签详情  """
class LabelsView(View):
    def get(self, request, id):
        label = Label.objects.get(id=id)
        users = []
        for i in label.users.all():
            users.append(i.id)
        question = label.questions.all()
        questions = []
        for i in question:
            labe = i.labels.all()
            labels = []
            for a in labe:
                labels.append(a.label_name)
            questions.append({
                'id': i.id,
                'createtime': str(i.createtime),
                'labels': labels,
                'reply': i.reply,
                'replyname': i.replyname,
                'replytime': i.replytime,
                'title': i.title,
                'unuseful_count': i.unuseful_count,
                'useful_count': i.useful_count,
                'user': i.user_id,
                'visits': i.visits
            })
        return JsonResponse({'id': label.id, 'questions': questions,
                             'label_name': label.label_name, 'desc': label.desc,
                             'baike_url': str(label.baike_url), 'label_icon': str(label.label_icon),
                             'users': users
                             })
